//
//  MapViewController.m
//  newTestGit
//
//  Created by fangjs on 16/2/16.
//  Copyright © 2016年 Hongshi. All rights reserved.
//

#import "MapViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "PinModel.h"

@interface MapViewController () <MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;

//地理反编码
@property (nonatomic, strong) CLGeocoder *geoC;

@end

@implementation MapViewController

- (CLGeocoder *) geoC {
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//移除所有的大头针
- (void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSArray *array = self.mapView.annotations;
    [self.mapView removeAnnotations:array];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    //1 .获取当前的触摸点
    CGPoint point = [[touches anyObject] locationInView:self.mapView];
    
    //2 .转换成经纬度
    CLLocationCoordinate2D pt = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];//将获取到的点转换成经纬度坐标
    
    //3 .添加大头针
    [self addAnnoWithPT:pt];

}

- (void) addAnnoWithPT:(CLLocationCoordinate2D) pt {
    
    __block PinModel *anno = [[PinModel alloc] init];
    anno.coordinate = pt;
    anno.title = @"王家玉";
    anno.subtitle = @"在此";
    
    //latitude:纬度 longitude:经度
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:anno.coordinate.latitude longitude:anno.coordinate.longitude];
    [self.geoC reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        CLPlacemark *pl = [placemarks firstObject];
        
        anno.title = pl.locality;//城市
        anno.subtitle = pl.thoroughfare ;//街道
        
        NSLog(@"%@",anno.title);
        NSLog(@"%@",anno.subtitle);
    
    }];
    
    [self.mapView addAnnotation:anno];
}

- (void) mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    
}

//当我们添加大头针时调用
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    
    return nil;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

































